package com.wuseguang.springcloud.config;

import net.minidev.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;


@Component
public class ProducerFallback implements FallbackProvider {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 返回值表示需要针对此微服务进行回退处理(必须是在注册中心中的service-id).
     * Zuul目前只支持服务级别的熔断，对具体某个URL的熔断暂不支持
     * @return
     */
    @Override
    public String getRoute() {
        return null; //服务Id ，若需要所有服务调用都支持回退，返回null 或者 * 即可
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        logger.error("url={},throwable={}",route,cause);
        return new ClientHttpResponse() {

            /**
             * 客户端向网关发送服务成功，网关向api服务请求失败，不应该把api的404 500 等问题抛给客户端
             * 网关和api服务对客户端来说都是黑盒子。
             * @return
             * @throws IOException
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK; //请求网关成功了，所以是ok
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }


            /**
             * 微服务出现宕机后，客户端再次请求就会返回fallback中的预设值
             * @return
             * @throws IOException
             */

            @Override
            public InputStream getBody() throws IOException {
                //服务异常时，输出此处内容，并打印错误日志
                logger.error("error appear -----------------");
                JSONObject json =new JSONObject();
                json.put("code","2000");
                json.put("msg","操作繁忙，请重试");
                json.put("data","{接口熔断}");
                return new ByteArrayInputStream(json.toJSONString().getBytes("UTF-8")); //返回前端的内容
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
